document.addEventListener('DOMContentLoaded', () => {
    const wsUrl = 'ws://localhost:12345/ws'; // 你的 WebSocket 服务器 URL
    const messagesContainer = document.getElementById('messages');
    const messageForm = document.getElementById('messageForm');
    const messageInput = document.getElementById('messageInput');

    const ws = new WebSocket(wsUrl);

    ws.onopen = () => {
        console.log('WebSocket connection opened');
    };

    ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        displayMessage(message);
    };

    ws.onclose = () => {
        console.log('WebSocket connection closed');
    };

    ws.onerror = (error) => {
        console.error('WebSocket error:', error);
    };

    messageForm.addEventListener('submit', (event) => {
        event.preventDefault();
        const messageText = messageInput.value;
        if (messageText.trim()) {
            const message = JSON.stringify({ content: messageText });
            ws.send(message);
            messageInput.value = '';
        }
    });

    function displayMessage(message) {
        const messageElement = document.createElement('span');
        messageElement.textContent = `[${message.sender || 'System'}] ${message.content}`;
        messagesContainer.appendChild(messageElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight; // Scroll to the bottom
    }
});
